package checks

import (
	"context"
	"fmt"

	"mongoscan/config"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func Precheck(cfg *config.Config) error {
	// 构建连接字符串
	var uri string
	if cfg.User != "" && cfg.Password != "" {
		uri = fmt.Sprintf("mongodb://%s:%s@%s:%d", cfg.User, cfg.Password, cfg.Host, cfg.Port)
	} else {
		uri = fmt.Sprintf("mongodb://%s:%d", cfg.Host, cfg.Port)
	}

	// 设置连接超时
	ctx, cancel := context.WithTimeout(context.Background(), cfg.Timeout)
	defer cancel()

	// 连接MongoDB
	clientOptions := options.Client().ApplyURI(uri)
	client, err := mongo.Connect(ctx, clientOptions)
	if err != nil {
		return fmt.Errorf("连接失败: %v", err)
	}
	defer client.Disconnect(ctx)

	// 测试连通性
	err = client.Ping(ctx, nil)
	if err != nil {
		return fmt.Errorf("ping失败: %v", err)
	}

	// 检查服务器状态权限
	if err := checkServerStatusPermission(ctx, client, cfg); err != nil {
		return err
	}

	fmt.Println("预检查通过")
	return nil
}

func checkServerStatusPermission(ctx context.Context, client *mongo.Client, cfg *config.Config) error {
	ctx, cancel := context.WithTimeout(ctx, cfg.Timeout)
	defer cancel()

	var result map[string]interface{}
	err := client.Database("admin").RunCommand(ctx, map[string]string{"serverStatus": "1"}).Decode(&result)
	if err != nil {
		return fmt.Errorf("权限不足, 无法获取服务器状态: %v", err)
	}
	return nil
}
